<template>
	<view>
		<!-- fixed头部 -->
		<view style="position:fixed;top:0;z-index: 99;" class="bg-white shadow">
			<!-- 自定义顶部 -->
			<view class="cu-custom bg-blue-1" :style="style">
				<!-- 顶部左侧打开抽屉 -->
				<view class="cu-left">
					<view class="bg-orange-1 left-rectangle"></view>
					<button class="cu-btn cuIcon bg-orange-2 shadow left-round" @click="modalName = 'DrawerModal'">
						{{tureWeek}}
					</button>
				</view>
				<!-- 顶部切换周数 -->
				<view class="cu-center">
					<button class="cu-btn round bg-green shadow week-btn" @click="modalName = 'ZcModal'">
						第{{weekIndex+1}}周-周{{title[thisDay-1]}}
					</button>
				</view>
				<view class="cu-right">

				</view>
			</view>
			<!-- 添加小程序提示 -->
			<add-tips src="/static/fav.jpg" :top="CustomBar" :duration="5"></add-tips>
			<!-- 课程上方星期 -->
			<view class="flex text-xs blue-1">
				<view style='width:10.4vw;' class="flex justify-center align-center">{{month}}</view>
				<view style='width:89.6vw;height:35rpx;' class="flex">
					<view v-for="(item, index) in title" :key='index' class="flex justify-center align-center flex-sub"
						:class="index==thisDay-1?'bg-gray orange-1':''">
						周{{item}}
					</view>
				</view>
			</view>
			<!-- 课程上方日期 -->
			<view class="flex text-xs blue-1">
				<view style='width:10.4vw;' class="flex justify-center align-center">月</view>
				<view style='width:89.6vw;height:35rpx' class="flex">
					<view v-for="(item, index) in dayArray" :key='index'
						class="flex justify-center align-center flex-sub"
						:class="index==thisDay-1?'bg-gray orange-1':''">
						{{item}}日
					</view>
				</view>
			</view>
		</view>
		<!-- 占位 -->
		<view :style="'height:calc('+ CustomBar+'px + 70rpx);'"></view>
		<!-- 课程区域 -->
		<scroll-view scroll-y="true" :style="marginHeight" style="width: 100vw;">
			<view :style="'background-image: url('+bacimg+');width: 100vw;'"
				class="padding-top-xs padding-bottom-sm flex course-bg" :class="bacimg?'':'bg-white'">
				<!-- 课程左侧时间 -->
				<view class='text-xs blue-1'>
					<view v-for="(item, index) in sksj" :key='index' class='flex justify-center align-center'
						style='height:120rpx;flex-direction:column;width:10.4vw;'>
						<view>{{index+1}}</view>
						<view class="text-grey">{{item.s}}</view>
						<view class="text-grey">{{item.e}}</view>
					</view>
				</view>
				<!-- 课程水平分割线 -->
				<view v-for="(item, index) in 11" :key='index'>
					<view style="width:89.6vw;position:absolute;border-bottom:1rpx solid lightgray;z-index: 0;"
						:style="'margin-top:'+(index+1)*120+'rpx;'">
					</view>
				</view>
				<!-- 课程主体区域 -->
				<view v-for="(item, index) in courseList" :key='index'>
					<view v-for="(subitem, subindex) in item.whichweekhave" :key="subindex">
						<view v-if='subitem===weekIndex+1'>
							<view class="kcb-item radius"
								:style="'margin-left:'+((item.whichDay-1)*12.8+0.4)+'vw;margin-right:0.4vw;margin-top:'+((item.whichSection)*120+5)+'rpx;height:'+(item.count*120-5)+'rpx;background-color:'+item.bg+';width:12vw;z-index: 9;'">
								<view class="text-white padding-xs" style="font-size:22rpx;">
									<view style="line-hight:24rpx;max-height:150rpx;overflow:hidden;">
										{{item.courseInfo}}
									</view>
								</view>
							</view>
						</view>
					</view>
				</view>
			</view>
		</scroll-view>
		<!-- 侧边栏设置 -->
		<view class="cu-modal drawer-modal justify-start" :class="modalName=='DrawerModal'?'show':''"
			@click="modalName = null">
			<view class="cu-dialog basis-lg bg-gradual-blue text-black" @tap.stop=""
				:style="[{top:CustomBar+'px',height:'calc(100vh - ' + CustomBar + 'px)'}]">
				<view class="margin-top-xl margin-bottom-xl shadow-lg">
					<view class="text-center text-white text-xl padding-bottom solids-bottom margin-bottom">
						<view>开学第
							<text class="text-sl padding-left-sm padding-right-sm">{{tureWeek}}</text>周
						</view>
					</view>
					<view class="cu-list menu sm-border card-menu margin-top margin-bottom">
						<view class="cu-item arrow" @click="bacChange">
							<view class="content">
								<view><text class="cuIcon-pic text-brown padding-right-sm"></text>自定义背景</view>
							</view>
						</view>
						<view class="cu-item arrow" @click="cancelImg">
							<view class="content">
								<view>
									<text class="cuIcon-close text-red padding-right-sm"></text>取消自定义
								</view>
							</view>
						</view>
					</view>
					<view class="cu-list menu sm-border card-menu margin-top margin-bottom">
						<view class="cu-item arrow" @click="setStartDay">
							<view class="content flex">
								<text class="cuIcon-settings text-grey"></text>
								设置开学日期
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>
		<!-- 周次model -->
		<view class="cu-modal bottom-modal" :class="modalName=='ZcModal'?'show':''">
			<view class="cu-dialog">
				<view class="cu-bar bg-white">
					<view class="action text-blue" @click="modalName = null">单选</view>
					<view class="action text-green" @click="modalName = null">确定</view>
				</view>
				<view class="grid col-4 padding-sm bg-gray">
					<view v-for="(item, index) in 20" :key="index" class="padding-xs" wx:key="week">
						<button class="cu-btn blue block" :class="weekIndex==index?'bg-blue':'line-blue'"
							@click="weekChange(index)">
							第{{index+1}}周
						</button>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import addTips from "@/components/add-tips/add-tips"
	import termPicker from '@/components/term-picker/term-picker'
	export default {
		data() {
			return {
				yearArray: [],
				termArray: [],
				xqm: "",
				xnm: "",
				CustomBar: this.CustomBar,
				StatusBar: this.StatusBar,
				modalName: "",
				weekIndex: 0, // 周数索引
				tureWeek: 0, // 真实周数
				dayArray: [], // 存放本周日期
				month: 1, //存放当前月
				title: ['一', '二', '三', '四', '五', '六', '日'],
				thisDay: 1, //今天周几
				bacimg: "",
				baseImg: "",
				sksj: [{
					's': '08:05',
					'e': '08:50'
				}, {
					's': '09:00',
					'e': '09:45'
				}, {
					's': '09:55',
					'e': '10:35'
				}, {
					's': '11:00',
					'e': '11:40'
				}, {
					's': '13:30',
					'e': '14:10'
				}, {
					's': '14:25',
					'e': '15:05'
				}, {
					's': '15:30',
					'e': '16:10'
				}, {
					's': '16:25',
					'e': '18:00'
				}],
				courseList: [],
				bgColor: [
					'#673AB7',
					'#4ADBC3',
					"#F05261",
					"#48A8E4",
					"#3F51B5"
				],
				//是否需要网络加载课程信息
				needNetLoad: true,
				// 存放开学日期
				startDayList: ['2021-03-01', '2021-07-19'],

			};
		},
		components: {
			addTips,
			termPicker
		},
		created() {
			// this.init()
		},
		methods: {
			init: function() {
				this.bacimg = wx.getStorageSync('bacimg') ? wx.getStorageSync('bacimg') : this.baseImg
				// 设置开学时间
				let value = wx.getStorageSync('start_day')
				if (!value) {
					let tempDay = this.startDayList[0].replace("-", "/").replace("-", "/")
					// console.log(temp_day)
					uni.setStorageSync('start_day', tempDay + ' 00:00:00')
					value = tempDay + ' 00:00:00'
				}
				// 计算相差天数判断周数
				// console.log('相差天数：' + this.dateMinus(value))
				let subWeek = parseInt(this.dateMinus(value) / 7) + 1;
				// 计算周数
				if (subWeek > 0 && subWeek < 21) {
					this.tureWeek = subWeek
					this.weekChange(subWeek - 1)
				} else {
					this.tureWeek = 1
					this.weekChange(0)
				}
				// 设置今天周几
				this.getDay()
				const courseList = uni.getStorageSync("courseList_" + this.weekIndex + 1)
				if (courseList) {
					this.courseList = courseList
					if (!courseList[0]['bg']) {
						wx.showModal({
							content: "为适配自定义课程背景，请重新导入课程",
							showCancel: false,
						})
					}
				}
				let postData = {
					'deptId': uni.getStorageSync("user_info").deptId,
					'weeknum': this.weekIndex + 1
				}

				this.$reqJson('wxapi/board', 'post', postData, res => {
					if (res.length > 0) {
						this.courseList = []
						for (let i = 0; i < 5; i++) {
							for (let j = 0; j < 8; j += 2) {
								if (res[i][j] !== '') {
									let randownBgColorIndex = Math.floor(Math.random() * (5 - 1) + 1) - 1
									let obj = {
										'courseInfo': res[i][j],
										//一天内的第几节课
										'whichSection': j,
										//一周中的第几周
										'whichDay': i + 1,
										//有几节课
										'count': 2,
										'bg': this.bgColor[randownBgColorIndex],
										// 哪一周有这节课
										'whichweekhave': [this.weekIndex + 1]
									}
									this.courseList.push(obj)
								}

							}
						}
					}
				})

			},
			xqmClick: function(e) {
				this.xqm = e
			},
			xnmClick: function(e) {
				this.xnm = e
			},
			coYearClick: function(yearArray, termArray) {
				this.yearArray = yearArray
				this.termArray = termArray
			},
			// 获取今天周几
			getDay: function() {
				let date = new Date();
				let day = date.getDay()
				if (day) {
					this.thisDay = day
				} else {
					this.thisDay = 7
				}
			},
			// 获取今天距离某天相差天数
			dateMinus: function(whichDay) {
				let sdate = new Date(whichDay);
				let now = new Date();
				let days = now.getTime() - sdate.getTime();
				let day = parseInt(days / (1000 * 60 * 60 * 24));
				return day;
			},
			// 周数变化,设置本周日期
			weekChange: function(index) {
				// console.log(index)
				let value = wx.getStorageSync('start_day')
				let myDate = new Date(value)
				myDate.setDate(myDate.getDate() + index * 7);

				let dayArray = []
				let mon = myDate.getMonth() + 1
				dayArray.push(this.$formatNumber(myDate.getDate()))
				for (let i = 0; i < 6; i++) {
					myDate.setDate(myDate.getDate() + 1)
					dayArray.push(this.$formatNumber(myDate.getDate()))
				}

				this.weekIndex = index
				this.dayArray = dayArray
				this.month = mon
				this.changeWeekLoadingCourse()
				this.modalName = null

			},
			changeWeekLoadingCourse: function() {
				const value = uni.getStorageSync("user_info")
				if (!value) {
					uni.showModal({
						content: "请登录后再使用！",
						showCancel: false,
					})
					return;
				}
				let postData = {
					'deptId': uni.getStorageSync("user_info").deptId,
					'weeknum': this.weekIndex + 1
				}
				this.$reqJson('wxapi/board', 'post', postData, res => {
					if (res.length > 0) {
						this.courseList = []
						for (let i = 0; i < 5; i++) {
							for (let j = 0; j < 8; j += 2) {
								if (res[i][j] !== '') {
									let randownBgColorIndex = Math.floor(Math.random() * (5 - 1) + 1) - 1
									let obj = {
										'courseInfo': res[i][j],
										//一天内的第几节课
										'whichSection': j,
										//一周中的第几周
										'whichDay': i + 1,
										//有几节课
										'count': 2,
										'bg': this.bgColor[randownBgColorIndex],
										// 哪一周有这节课
										'whichweekhave': [this.weekIndex + 1]
									}
									this.courseList.push(obj)
								}

							}
						}
					}
				})

			},
			// 获取课表
			getCourse: function() {
				this.modalName = null
				const value = uni.getStorageSync('user_info')
				if (value) {
					let postData = {
						username: value.username,
						password: value.password,
						xnm: this.xnm,
						xqm: this.xqm,
					}
					this.$req("api/study/course/", "post", postData, res => {
						uni.setStorageSync('course_list', res.data.course_list)
						// const customCourse = uni.getStorageSync('CUSTOM-COURSE')
						// if (customCourse) {
						//     res.data.course_list.push(...customCourse)
						// }
						this.courseList = res.data.course_list
					})
				} else {
					uni.showModal({
						content: "请先登录账号",
						showCancel: false,
					})
				}

			},
			// 添加课程
			addCourse: function() {
				uni.navigateTo({
					url: "/pages/course/addcourse/addcourse",
					fail: res => {
						console.log(res)
					}
				})
			},
			// 背景图片设置
			bacChange: function(res) {
				var that = this
				uni.chooseImage({
					count: 1,
					success: res => {
						uni.getFileSystemManager().readFile({
							filePath: res.tempFilePaths[0], //选择图片返回的相对路径
							encoding: 'base64', //编码格式
							success: res => { //成功的回调
								// console.log('data:image/png;base64,' + res.data)
								var len = ('data:image/png;base64,' + res.data).length
								// console.log(len)
								if (len < 1048576) {
									this.bacimg = 'data:image/png;base64,' + res.data
									this.modalName = null
									uni.setStorageSync('bacimg', 'data:image/png;base64,' +
										res.data)
								} else {
									uni.showModal({
										content: '选择的图片大小超过限制!',
										showCancel: false,
									})
								}
							}
						})
					}
				})
			},
			cancelImg() {
				uni.setStorageSync('bacimg', '')
				this.bacimg = this.baseImg
				this.modalName = null
			},
			setStartDay: function() {
				uni.showActionSheet({
					itemList: this.startDayList,
					success: res => {
						let value = this.startDayList[res.tapIndex]
						value = value.replace('-', '/').replace('-', '/')
						uni.setStorageSync('start_day', value + ' 00:00:00')
						this.init()
					},
					fail(res) {
						console.log(res.errMsg)
					}
				})
			},
			// 显示课程点击详情
			showDetail: function(index) {
				console.log(index)
				const str = '地点：' + this.courseList[index].cdmc + '\n' +
					'教师：' + this.courseList[index].xm + '\n' +
					'周次：' + this.courseList[index].zcdd + '\n' +
					'学分：' + (this.courseList[index].xf ? this.courseList[index].xf : '空')
				uni.showModal({
					title: this.courseList[index].kcmc,
					content: str,
					showCancel: true,
					confirmText: '删除',
					success: res => {
						if (res.confirm) {
							uni.showModal({
								content: '是否确认删除？',
								success: res => {
									if (res.confirm) {
										let value = uni.getStorageSync('course_list')
										value.splice(index, 1)
										this.courseList = value
										uni.setStorageSync('course_list', value)
									}
								}
							})
						}
					}
				})
			}
		},
		computed: {
			style() {
				let StatusBar = this.StatusBar;
				let CustomBar = this.CustomBar;
				let value = StatusBar + CustomBar
				let style = `height:${CustomBar}px;`;
				return style
			},
			marginHeight() {
				let StatusBar = this.StatusBar;
				let CustomBar = this.CustomBar;
				let style = `height:calc(100vh - 100rpx - env(safe-area-inset-bottom) / 2 - ${CustomBar}px - 70rpx);`;
				return style
			}
		},
	}
</script>

<style lang="scss">
	.cu-custom {
		width: 100vw;
		display: flex;
		flex-direction: row;
		justify-content: space-between;
		// align-items: ;

		// 顶部左侧打开抽屉
		.cu-left {
			width: 25vw;
			display: flex;
			flex-direction: row;

			position: relative;

			.left-rectangle {
				height: 50rpx;
				width: 80rpx;

				position: absolute;
				bottom: 14rpx;
			}

			.left-round {
				width: 66rpx;
				height: 66rpx;
				border-radius: 50%;

				box-shadow: 0 0 1rpx;

				position: absolute;
				left: 50rpx;
				bottom: 6rpx;

				display: flex;
				flex-direction: row;
				justify-content: center;
				align-items: center;
			}
		}

		.cu-center {
			width: 50vw;
			display: flex;
			flex-direction: row;
			justify-content: center;
			align-items: center;

			position: relative;

			.week-btn {
				position: absolute;
				bottom: 10rpx;
			}
		}

		.cu-right {
			width: 25vw;
		}
	}

	.course-bg {
		background-size: cover;
		background-position: center center;
	}

	.kcb-item {
		position: absolute;
		justify-content: center;
		display: flex;
		align-items: center;
	}
</style>
